//
//  NetworkStatusManager.swift
//  ClockWidget
//
//  Created by TSYH on 2023/7/26.
//

import Alamofire

public class NetworkStatusManager {
    public static let shared = NetworkStatusManager()
    private let networkReachability = NetworkReachabilityManager.default!
    private var networkStatus: NetworkReachabilityManager.NetworkReachabilityStatus?
    
    init() {
        networkReachability.startListening { [weak self] status in
            self?.networkStatus = status
            self?.listeners.forEach { action in
                action(status)
            }
        }
    }
    
    var listeners = [NetworkReachabilityManager.Listener]()
    public func startListening(listener: @escaping NetworkReachabilityManager.Listener) {
        listeners.append(listener)
        
        // 添加监听之前，网络授权已完成，主动调一次
        if let status = self.networkStatus {
            listener(status)
        }
    }
    
    // 是否有网络
    public var isValidNetwork: Bool {
        if case .reachable(_) = networkReachability.status {
            return true
        }
        return false
    }
}
